package com.cma.cmabackend.service;

import com.cma.cmabackend.dao.TypeDao;
import com.cma.cmabackend.entity.Category;
import com.cma.cmabackend.entity.Type;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;


@Service
public class TypeService {
    @Resource
    TypeDao typeDao;
    @Resource
    CategoryService categoryService;

    public boolean isExist(String type) {
        Type type1 = typeDao.findByTypeName(type);
        return type1 != null;
    }

    public Type addType(String type, String category) {
        Type type1 = new Type();
        type1.setTypeName(type);
        Type type2 = typeDao.save(type1);
        //添加category
        Category category1 = categoryService.findCategoryByName(category);
        category1.getTypes().add(type2);
        categoryService.save(category1);
        return type1;
    }

    public String getTypeNameById(int id) {
        return Objects.requireNonNull(typeDao.findById(id).orElse(null)).getTypeName();
    }

    public int getTypeIdOrAdd(String type, String category) {
        if (!isExist(type)) {
            return addType(type, category).getId();
        } else {
            Type type1 = typeDao.findByTypeName(type);
            return type1.getId();
        }
    }
}

